<template>
  <div class="orders-container">
    <div class="orders-header">
      <h2>我的订单</h2>
      <div class="order-tabs">
        <el-tabs v-model="activeTab" @tab-click="handleTabClick">
          <el-tab-pane label="全部订单" name="all"></el-tab-pane>
          <el-tab-pane label="待付款" name="1"></el-tab-pane>
          <el-tab-pane label="待派送" name="2"></el-tab-pane>
          <el-tab-pane label="已派送" name="3"></el-tab-pane>
          <el-tab-pane label="已完成" name="4"></el-tab-pane>
          <el-tab-pane label="已取消" name="5"></el-tab-pane>
        </el-tabs>
      </div>
    </div>

    <!-- 订单列表 -->
    <div class="orders-content">
      <el-empty v-if="orderList.length === 0" description="暂无订单记录" :image-size="200">
        <el-button type="primary" @click="$router.push('/home/products')">去购物</el-button>
      </el-empty>

      <div v-else class="order-list">
        <div v-for="order in orderList" :key="order.id" class="order-card">
          <div class="order-header">
            <div class="order-info">
              <span class="order-time">{{ formatDate(order.orderTime) }}</span>
              <span class="order-number">订单号：{{ order.number }}</span>
            </div>
            <div class="order-status" :class="`status-${order.status}`">
              {{ getStatusText(order.status) }}
            </div>
          </div>

          <div class="order-items">
            <div v-for="(item, index) in order.orderDetails" :key="index" class="order-item">
              <div class="item-image">
                <img :src="getFullImageUrl(item.image)" :alt="item.name">
              </div>
              <div class="item-info">
                <div class="item-name">{{ item.name }}</div>
                <div v-if="item.dishFlavor" class="item-flavor">{{ formatFlavor(item.dishFlavor) }}</div>
              </div>
              <div class="item-price">¥{{ item.amount }}</div>
              <div class="item-quantity">x{{ item.number }}</div>
            </div>
          </div>

          <div class="order-footer">
            <div class="order-address">
              <i class="fas fa-map-marker-alt"></i>
              <span>{{ order.consignee }} {{ order.phone }}</span>
              <span class="address-detail">{{ order.address }}</span>
            </div>
            <div class="order-total">
              <span>共{{ getTotalItems(order.orderDetails) }}件商品</span>
              <span class="total-amount">实付：<strong>¥{{ order.amount }}</strong></span>
            </div>
            <div class="order-actions">
              <el-button
                  v-if="order.status === 1"
                  type="danger"
                  size="small"
                  @click="cancelOrder(order.id)"
              >
                取消订单
              </el-button>
              <el-button
                  v-if="order.status === 1"
                  type="primary"
                  size="small"
                  @click="payOrder(order)"
              >
                去支付
              </el-button>
              <el-button
                  v-if="order.status === 3"
                  type="success"
                  size="small"
                  @click="confirmOrder(order.id)"
              >
                确认收货
              </el-button>
              <el-button
                  v-if="order.status === 4"
                  type="primary"
                  size="small"
                  @click="repeatOrder(order.id)"
              >
                再来一单
              </el-button>
              <el-button
                  type="info"
                  size="small"
                  @click="showOrderDetail(order)"
              >
                订单详情
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-container" v-if="orderList.length > 0">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[5, 10, 20, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 订单详情对话框 -->
    <el-dialog
        v-model="detailDialogVisible"
        title="订单详情"
        width="700px"
        destroy-on-close
    >
      <div v-if="currentOrder" class="order-detail">
        <div class="detail-section">
          <h3>订单信息</h3>
          <div class="detail-item">
            <span class="label">订单编号：</span>
            <span class="value">{{ currentOrder.number }}</span>
          </div>
          <div class="detail-item">
            <span class="label">下单时间：</span>
            <span class="value">{{ formatDateTime(currentOrder.orderTime) }}</span>
          </div>
          <div class="detail-item">
            <span class="label">支付方式：</span>
            <span class="value">{{ currentOrder.payMethod === 1 ? '微信支付' : '支付宝' }}</span>
          </div>
          <div class="detail-item">
            <span class="label">订单状态：</span>
            <span class="value status" :class="`status-${currentOrder.status}`">
              {{ getStatusText(currentOrder.status) }}
            </span>
          </div>
          <div class="detail-item" v-if="currentOrder.remark">
            <span class="label">订单备注：</span>
            <span class="value">{{ currentOrder.remark }}</span>
          </div>
        </div>

        <div class="detail-section">
          <h3>收货信息</h3>
          <div class="detail-item">
            <span class="label">收货人：</span>
            <span class="value">{{ currentOrder.consignee }}</span>
          </div>
          <div class="detail-item">
            <span class="label">联系电话：</span>
            <span class="value">{{ currentOrder.phone }}</span>
          </div>
          <div class="detail-item">
            <span class="label">收货地址：</span>
            <span class="value">{{ currentOrder.address }}</span>
          </div>
        </div>

        <div class="detail-section">
          <h3>商品信息</h3>
          <div class="detail-items">
            <div class="detail-item-header">
              <span class="col-product">商品信息</span>
              <span class="col-price">单价</span>
              <span class="col-quantity">数量</span>
              <span class="col-subtotal">小计</span>
            </div>
            <div v-for="(item, index) in currentOrder.orderDetails" :key="index" class="detail-item-row">
              <div class="col-product">
                <div class="product-image">
                  <img :src="getFullImageUrl(item.image)" :alt="item.name">
                </div>
                <div class="product-info">
                  <div class="product-name">{{ item.name }}</div>
                  <div v-if="item.dishFlavor" class="product-flavor">{{ formatFlavor(item.dishFlavor) }}</div>
                </div>
              </div>
              <div class="col-price">¥{{ item.amount }}</div>
              <div class="col-quantity">{{ item.number }}</div>
              <div class="col-subtotal">¥{{ (item.amount * item.number).toFixed(2) }}</div>
            </div>
          </div>
        </div>

        <div class="detail-section detail-summary">
          <div class="summary-item">
            <span>商品总额：</span>
            <span>¥{{ getItemsTotal(currentOrder.orderDetails).toFixed(2) }}</span>
          </div>
          <div class="summary-item">
            <span>配送费：</span>
            <span>¥{{ getDeliveryFee(currentOrder).toFixed(2) }}</span>
          </div>
          <div class="summary-total">
            <span>实付金额：</span>
            <span class="total-price">
      {{ (currentOrder.status === 1 || currentOrder.status === 5) ? '¥0.00' : '¥' + currentOrder.amount }}
    </span>
          </div>
        </div>

        <div class="detail-actions">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button
              v-if="currentOrder.status === 1"
              type="primary"
              @click="payOrder(currentOrder); detailDialogVisible = false"
          >
            去支付
          </el-button>
          <el-button
              v-if="currentOrder.status === 4"
              type="success"
              @click="repeatOrder(); detailDialogVisible = false"
          >
            再来一单
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted} from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  getOrderList,
  getOrderDetail,
  cancelOrder as apiCancelOrder,
  confirmOrder as apiConformOrder,
  payOrderApi
} from '@/api/order';
import {fileViewPath} from "@/utils/file";

const router = useRouter();

// 订单列表数据
const orderList = ref([]);
const activeTab = ref('all');
const currentPage = ref(1);
const pageSize = ref(5);
const total = ref(0);

// 订单详情相关
const detailDialogVisible = ref(false);
const currentOrder = ref(null);

// 获取订单列表
const fetchOrderList = async () => {
  try {
    const params = {
      pageNo: currentPage.value,
      pageSize: pageSize.value,
      status: activeTab.value === 'all' ? '' : activeTab.value
    };

    const res = await getOrderList(params);
    if (res.code === '200') {
      orderList.value = res.data.records || [];
      total.value = res.data.total || 0;
    } else {
      ElMessage.error(res.msg || '获取订单列表失败');
    }
  } catch (error) {
    console.error('获取订单列表失败:', error);
    ElMessage.error('获取订单列表失败');
  }
};

// 获取订单详情
const fetchOrderDetail = async (orderId) => {
  try {
    const res = await getOrderDetail(orderId);
    if (res.code === '200') {
      return res.data;
    } else {
      ElMessage.error(res.msg || '获取订单详情失败');
      return null;
    }
  } catch (error) {
    console.error('获取订单详情失败:', error);
    ElMessage.error('获取订单详情失败');
    return null;
  }
};

// 显示订单详情
const showOrderDetail = async (order) => {
  // 如果订单已经包含详情信息，直接显示
  if (order.orderDetails && order.orderDetails.length > 0) {
    currentOrder.value = order;
    detailDialogVisible.value = true;
    return;
  }

  // 否则请求详情信息
  const detail = await fetchOrderDetail(order.id);
  if (detail) {
    currentOrder.value = detail;
    detailDialogVisible.value = true;
  }
};

// 取消订单
const cancelOrder = async (orderId) => {
  try {
    await ElMessageBox.confirm(
        '确定要取消该订单吗？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    );

    const res = await apiCancelOrder(orderId);
    if (res.code === '200') {
      ElMessage.success('订单已取消');
      await fetchOrderList(); // 刷新订单列表
    } else {
      ElMessage.error(res.msg || '取消订单失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消订单失败:', error);
      ElMessage.error('取消订单失败');
    }
  }
};

// 确认收货
const confirmOrder = async (orderId) => {
  try {
    await ElMessageBox.confirm(
        '确认已收到商品吗？',
        '提示',
        {
          confirmButtonText: '确认收货',
          cancelButtonText: '取消',
          type: 'info'
        }
    );
    //确认收货api
    const res = await apiConformOrder(orderId);
    if (res.code === '200') {
      ElMessage.success('已确认收货');
      await fetchOrderList(); // 刷新订单列表
    } else {
      ElMessage.error(res.msg || '确认收货失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('确认收货失败:', error);
      ElMessage.error('确认收货失败');
    }
  }
};

// 再来一单
const repeatOrder = async () => {
  //直接跳转到商品页
  await router.push('/home/products');
};

// 去支付
const payOrder = async (order) => {
  try {
    // 弹窗确认支付
    await ElMessageBox.confirm(
        `确认支付订单：${order.number}，金额：¥${order.amount}？`,
        '支付确认',
        {
          confirmButtonText: '确认支付',
          cancelButtonText: '取消',
          type: 'warning'
        }
    );

    // 调用支付API
    const res = await payOrderApi(order.id);
    if (res.code === '200') {
      ElMessage.success('支付成功');
      // 支付成功后刷新订单列表
      await fetchOrderList();

      // 如果当前在订单详情页，关闭详情对话框
      if (detailDialogVisible.value) {
        detailDialogVisible.value = false;
      }
    } else {
      ElMessage.error(res.msg || '支付失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('支付失败:', error);
      ElMessage.error('支付失败，请稍后重试');
    }
  }
};

// 处理标签页切换
const handleTabClick = () => {
  currentPage.value = 1; // 切换标签时重置页码
  fetchOrderList();
};

// 处理分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchOrderList();
};

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchOrderList();
};

// 获取订单状态文本
const getStatusText = (status) => {
  const statusMap = {
    1: '待付款',
    2: '待派送',
    3: '已派送',
    4: '已完成',
    5: '已取消'
  };
  return statusMap[status] || '未知状态';
};

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

// 格式化日期时间
const formatDateTime = (dateStr) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  return `${formatDate(dateStr)} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
};

// 格式化口味信息
const formatFlavor = (flavorJson) => {
  try {
    const flavors = JSON.parse(flavorJson);
    return Object.entries(flavors)
        .map(([key, value]) => `${key}: ${value}`)
        .join(', ');
  } catch (e) {
    return flavorJson;
  }
};

// 获取图片完整URL
const getFullImageUrl = (imagePath) => {
  if (!imagePath) return '';
  return `${fileViewPath}${formatImagePath(imagePath)}`;
};

// 格式化图片路径
const formatImagePath = (path) => {
  if (!path) return '';
  return path.replace(/\\/g, '/');
};

// 计算订单中的商品总数
const getTotalItems = (items) => {
  if (!items || items.length === 0) return 0;
  return items.reduce((sum, item) => sum + item.number, 0);
};

// 计算订单中的商品总金额
const getItemsTotal = (items) => {
  if (!items || items.length === 0) return 0;
  return items.reduce((sum, item) => sum + (item.amount * item.number), 0);
};

// 计算配送费
const getDeliveryFee = (order) => {
  // 如果订单已取消，配送费显示为0
  if (order.status === 5) {
    return 0;
  }

  // 如果订单未支付，配送费也显示为0
  if (order.status === 1) {
    return 0;
  }

  // 正常订单计算配送费
  const itemsTotal = getItemsTotal(order.orderDetails);
  return order.amount - itemsTotal;
};

// 组件挂载时获取订单列表
onMounted(() => {
  fetchOrderList();
});
</script>

<style scoped>
.orders-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.orders-header {
  margin-bottom: 20px;
}

.orders-header h2 {
  margin-bottom: 20px;
  color: #333;
  font-size: 24px;
  text-align: center;
}

.order-tabs {
  margin-bottom: 20px;
}

.order-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
  overflow: hidden;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background-color: #f8f8f8;
  border-bottom: 1px solid #eee;
}

.order-info {
  display: flex;
  align-items: center;
}

.order-time {
  margin-right: 20px;
  color: #666;
}

.order-number {
  color: #333;
  font-weight: bold;
}

.order-status {
  font-weight: bold;
}

.status-1 {
  color: #e6a23c;
}

.status-2 {
  color: #409eff;
}

.status-3 {
  color: #67c23a;
}

.status-4 {
  color: #909399;
}

.status-5 {
  color: #f56c6c;
}

.order-items {
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
}

.order-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  padding-bottom: 10px;
  border-bottom: 1px dashed #eee;
}

.order-item:last-child {
  margin-bottom: 0;
  padding-bottom: 0;
  border-bottom: none;
}

.item-image {
  width: 60px;
  height: 60px;
  margin-right: 15px;
  border-radius: 4px;
  overflow: hidden;
}

.item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.item-info {
  flex: 1;
}

.item-name {
  font-weight: bold;
  margin-bottom: 5px;
}

.item-flavor {
  color: #666;
  font-size: 12px;
}

.item-price {
  margin: 0 20px;
  color: #ff6b6b;
  font-weight: bold;
}

.item-quantity {
  color: #666;
  margin-left: 10px;
}

.order-footer {
  padding: 15px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
}

.order-address {
  flex: 1;
  display: flex;
  align-items: center;
  color: #666;
}

.order-address i {
  margin-right: 5px;
  color: #ff6b6b;
}

.address-detail {
  margin-left: 10px;
}

.order-total {
  margin: 0 20px;
  text-align: right;
}

.total-amount {
  margin-left: 10px;
  color: #ff6b6b;
}

.order-actions {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

/* 订单详情样式 */
.order-detail {
  padding: 10px;
}

.detail-section {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.detail-section h3 {
  margin-bottom: 15px;
  font-size: 18px;
  color: #333;
  padding-bottom: 10px;
  border-bottom: 1px dashed #eee;
}

.detail-item {
  display: flex;
  margin-bottom: 10px;
}

.detail-item .label {
  width: 100px;
  color: #666;
}

.detail-item .value {
  flex: 1;
}

.detail-item .status {
  font-weight: bold;
}

.detail-items {
  border: 1px solid #eee;
  border-radius: 4px;
}

.detail-item-header {
  display: flex;
  padding: 10px;
  background-color: #f8f8f8;
  font-weight: bold;
  color: #666;
}

.detail-item-row {
  display: flex;
  padding: 15px 10px;
  border-top: 1px solid #eee;
  align-items: center;
}

.col-product {
  flex: 3;
  display: flex;
  align-items: center;
}

.col-price, .col-quantity, .col-subtotal {
  flex: 1;
  text-align: center;
}

.product-image {
  width: 50px;
  height: 50px;
  margin-right: 10px;
  border-radius: 4px;
  overflow: hidden;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-name {
  font-weight: bold;
  margin-bottom: 5px;
}

.product-flavor {
  color: #666;
  font-size: 12px;
}

.detail-summary {
  border-bottom: none;
}

.summary-item {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 10px;
  color: #666;
}

.summary-item span:first-child {
  margin-right: 20px;
}

.summary-total {
  display: flex;
  justify-content: flex-end;
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #eee;
  font-weight: bold;
}

.summary-total span:first-child {
  margin-right: 20px;
}

.total-price {
  color: #ff6b6b;
  font-size: 18px;
}

.detail-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>